<template>
	<div class="container">
		<v-md-editor v-model="data.content" mode="preview"></v-md-editor>
		<div class="bottom">
			<span class="time" :class="!$store.state.userinfo ? 'right-time' : ''"
				>发布时间：{{ formatPast(data.createTime, "-") }}</span
			>
			<el-button
				class="operation"
				text
				type="danger"
				@click="dialogVisible = true"
				v-if="$store.state.userinfo"
				>删除文章</el-button
			>
			<el-button
				class="operation"
				text
				@click="$router.push(`/write/${data.id}`)"
				v-if="$store.state.userinfo"
				>编辑文章</el-button
			>
		</div>
	</div>
	<el-dialog title="删除" v-model="dialogVisible" width="30%">
		<p>是否删除该文章？</p>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false" style="margin-right: 15px"
					>取消</el-button
				>
				<el-button type="danger" @click="delArticle">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
import { onUnmounted, ref } from "vue";
import router from "@/router";
import { GetArticleById, DeleteArticle } from "@/api/request";
import { ElMessage, ElButton, ElDialog } from "element-plus";
import "element-plus/es/components/button/style/css";
import "element-plus/es/components/dialog/style/css";
import { formatPast } from "@/utils";
const dialogVisible = ref(false);
// 获取路由传参
const id = router.currentRoute.value.params.id;
const data = ref({
	title: "",
	content: "",
	createTime: "",
});
const getArticle = () => {
	GetArticleById(id).then((res) => {
		if (res.success) {
			data.value = res.data;
			document.title = data.value.title;
		} else {
			router.push("/404");
		}
	});
};
getArticle();

const delArticle = () => {
	DeleteArticle(id).then((res) => {
		if (res.success) {
			ElMessage.success("删除成功");
			router.push("/");
		} else {
			ElMessage.error(res.msg);
		}
		dialogVisible.value = false;
	});
};
</script>

<style scoped lang="less">
.bottom {
	display: flex;
	align-items: center;
	margin-top: 20px;
	padding: 0 40px;
	margin-bottom: 50px;
}
.time {
	margin-right: auto;
}
.right-time {
	margin-right: 0;
	margin-left: auto;
}
.el-button + .el-button {
	margin-left: 0;
}
// 适配手机
@media screen and (max-width: 768px) {
	.operation {
		display: none;
	}
}
</style>
